function minCost(basket1, basket2) {
  const countMap = new Map();

  // 统计每个数字在两个果篮中出现的总次数
  for (const num of basket1) {
    countMap.set(num, (countMap.get(num) || 0) + 1);
  }
  for (const num of basket2) {
    countMap.set(num, (countMap.get(num) || 0) + 1);
  }

  // 检查是否所有数字的出现次数都是偶数，如果有奇数则无法平均分配
  for (const [num, count] of countMap) {
    if (count % 2 !== 0) {
      return -1;
    }
  }

  // 计算每个果篮中应该有的每个数字的数量（总数量的一半）
  const targetCount = new Map();
  for (const [num, count] of countMap) {
    targetCount.set(num, count / 2);
  }

  // 计算basket1中每个数字的当前数量
  const count1 = new Map();
  for (const num of basket1) {
    count1.set(num, (count1.get(num) || 0) + 1);
  }

  // 确定需要从basket1中移除的数字和需要添加到basket1中的数字
  const excess = []; // 从basket1中移除的数字
  const deficit = []; // 需要添加到basket1中的数字

  for (const [num, target] of targetCount) {
    const current = count1.get(num) || 0;
    const diff = current - target;
    if (diff > 0) {
      // 需要从basket1中移除diff个num
      for (let i = 0; i < diff; i++) {
        excess.push(num);
      }
    } else if (diff < 0) {
      // 需要向basket1中添加-diff个num
      for (let i = 0; i < -diff; i++) {
        deficit.push(num);
      }
    }
  }

  // 排序以实现最优匹配：小的 excess 与大的 deficit 匹配
  excess.sort((a, b) => a - b);
  deficit.sort((a, b) => b - a);

  // 找到最小的数字，可能作为中介使用
  let minNum = Infinity;
  for (const num of countMap.keys()) {
    minNum = Math.min(minNum, num);
  }

  let totalCost = 0;
  for (let i = 0; i < excess.length; i++) {
    // 计算两种交换方式的成本并选择较小的
    const directCost = Math.min(excess[i], deficit[i]);
    const mediatorCost =
      Math.min(excess[i], minNum) + Math.min(deficit[i], minNum);
    totalCost += Math.min(directCost, mediatorCost);
  }

  return totalCost;
}

// 测试示例
console.log(minCost([4, 2, 2, 2], [1, 4, 1, 2])); // 输出: 1
console.log(minCost([2, 3, 4, 1], [3, 2, 5, 1])); // 输出: -1
